package com.hxk.sso.server.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@Order(1)  // 设置配置类的加载顺序为1
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    PasswordEncoder passwordEncoder() {
        // 返回一个BCryptPasswordEncoder实例作为密码编码器
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 忽略某些路径的认证
        web.ignoring()
           .antMatchers("/login.html", "/css/**", "/js/**", "/images/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 配置需要进行安全检查的请求
        http.requestMatchers()
            .antMatchers("/login", "/oauth/authorize")  // 匹配"/login"和"/oauth/authorize"路径
            .and()
            .authorizeRequests()  // 开始配置授权请求
            .anyRequest()  // 对所有请求进行配置
            .authenticated()  // 要求所有请求都经过认证
            .and()
            .formLogin()  // 开始配置表单登录
            .loginPage("/login.html")  // 设置登录页面为"/login.html"
            .loginProcessingUrl("/login")  // 设置登录处理URL为"/login"
            .permitAll()  // 允许所有用户访问登录页面和处理URL
            .and()
            .csrf()  // 开始配置跨站请求伪造（CSRF）防护
            .disable();  // 禁用CSRF防护
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 使用内存中的身份验证配置
        auth.inMemoryAuthentication()
            .withUser("test")  // 添加一个用户名为"test"的用户
            .password(passwordEncoder().encode("123"))  // 设置用户密码，使用passwordEncoder进行编码
            .roles("admin");  // 设置用户角色为"admin"
    }
}
